package com.itheima.ai.controller;

import com.itheima.ai.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;

//AI对话
@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class CustomerServiceController {
    private final ChatClient serviceChatClient;

    private final ChatHistoryRepository chatHistoryRepository;
    //阻塞式
//    @RequestMapping(value = "/service",produces = "text/html;charset=utf-8")
//    public String chat(String prompt,String chatId) {
//        //1.保存会话id
//        chatHistoryRepository.save("service",chatId);
//
//        //2.请求模型
//        return serviceChatClient.prompt()
//                .user(prompt)  //设置用户输入
//                .advisors(a->a.param(CHAT_MEMORY_CONVERSATION_ID_KEY,chatId))  //设置会话ID
//                .call()  //调用模型
//                .content();  //获取模型的响应内容
//    }

    //流式
    @RequestMapping(value = "/service",produces = "text/html;charset=utf-8")
    public Flux<String> chat1(String prompt, String chatId) {   //这种方法在浏览器中无法显示，因为浏览器不支持流式响应（智能客服处会报错）
        //1.保存会话id
        chatHistoryRepository.save("service",chatId);
        //2.请求模型
        return serviceChatClient.prompt()
                .user(prompt)
                .advisors(a->a.param(CHAT_MEMORY_CONVERSATION_ID_KEY,chatId))
                .stream()
                .content();
    }
}
